#include "slist.h"

SListNode* BuySListNode(SLTDateType x) {
	SListNode* newnode = (SListNode*)malloc(sizeof(SListNode));
	if (newnode == NULL) {
		perror("malloc fail\n");
		exit(-1);
	}
	newnode->data = x;
	newnode->next = NULL;
	return newnode;
}

void SListPrint(SListNode* plist) {
	SListNode* cur = plist;
	while (cur)
	{
		printf("%d->", cur->data);
		cur = cur->next;
	}
	printf("NULL\n");
}

void SListPushBack(SListNode** pplist, SLTDateType x) {
	SListNode* newnode = BuySListNode(x);
	if (*pplist == NULL) {
		*pplist = newnode;
	}
	else {
		SListNode* tail = *pplist;
		while (tail->next != NULL) {
			tail = tail->next;
		}
		tail->next = newnode;
	}
}

void SListPushFront(SListNode** pplist, SLTDateType x) {
	SListNode* newnode = BuySListNode(x);
	newnode->next = *pplist;
	*pplist = newnode;
}

void SListPopBack(SListNode** pplist) {
	assert(*pplist);
	if ((*pplist)->next == NULL) {
		*pplist = NULL;
	}
	else {
		SListNode* tail = *pplist, *tailPrev = NULL;
		while (tail->next) {
			tailPrev = tail;
			tail = tail->next;
		}
		free(tail);
		tail = NULL;
		tailPrev->next = NULL;
	}
}

void SListPopFront(SListNode** pplist) {
	assert(*pplist);
	SListNode* newnode = (*pplist)->next;
	free(*pplist);
	*pplist = newnode;
}

SListNode* SListFind(SListNode* plist, SLTDateType x) {
	SListNode* cur = plist;
	while (cur) {
		if (cur->data == x) {
			return cur;
		}
		cur = cur->next;
	}
	return NULL;
}

void SListInsertAfter(SListNode* pos, SLTDateType x) {
	assert(pos);
	SListNode* newnode = BuySListNode(x);
	newnode->next = pos->next;
	pos->next = newnode;
}

void SListEraseAfter(SListNode* pos) {
	assert(pos);
	assert(pos->next);
	SListNode* posNext = pos->next;
	pos->next = posNext->next;
	free(posNext);
	posNext = NULL;
}

void SListDestroy(SListNode* plist) {
	SListNode* phead = plist;
	SListNode* next = NULL;
	if (phead)
		next = phead->next;
	while (next) {
		free(phead);
		phead = NULL;
		phead = next;
		next = next->next;
	}
}